#include "bsp_delay.h"
#include "RTT_DEBUG.h"
/* 延时宏 */
#define STEP_DELAY_MS                    50




/* 延时变量 */
static __IO uint32_t fac_us;
static __IO uint32_t fac_ms;

/* 初始化滴答定时器 */
void bsp_delay_init(void)
{
	/* 配置时钟源 */
	systick_clock_source_config(SYSTICK_CLOCK_SOURCE_AHBCLK_NODIV); // 内部时钟8M
	fac_us = system_core_clock / (1000000U);
	fac_ms = fac_us * (1000U);

	DBG_log("delay init");
}

/* 微妙延时 */
void bsp_delay_us(uint32_t nus)
{
	uint32_t temp = 0;
	SysTick->LOAD = (uint32_t)(nus * fac_us);
	SysTick->VAL = 0x00;
	SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk ;
	do
	{
		temp = SysTick->CTRL;
	}while((temp & 0x01) && !(temp & (1 << 16)));
	SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
	SysTick->VAL = 0x00;
}


/* 毫秒延时 */
void bsp_delay_ms(uint16_t nms)
{
	uint32_t temp = 0;
	while(nms)
	{
		if(nms > STEP_DELAY_MS)
		{
			SysTick->LOAD = (uint32_t)(STEP_DELAY_MS * fac_ms);
			nms -= STEP_DELAY_MS;
		}
		else
		{
			SysTick->LOAD = (uint32_t)(nms * fac_ms);
			nms = 0;
		}
		SysTick->VAL = 0x00;
		SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk;
		do
		{
			temp = SysTick->CTRL;
		}while((temp & 0x01) && !(temp & (1 << 16)));
		SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
		SysTick->VAL = 0x00;
	}
}


/* 秒延时 */
void bsp_delay_sec(uint16_t sec)
{
	uint16_t index;
	for(index = 0; index < sec; index++)
	{
		bsp_delay_ms(500);
		bsp_delay_ms(500);
	}
}

